package org.example.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.annotation.CheckPermission;
import org.example.context.BaseContext;
import org.springframework.stereotype.Component;

import java.nio.file.AccessDeniedException;
import java.util.Arrays;

@Aspect
@Component
public class PermissionAspect {

/*    *//**
     * 定义切入点：拦截所有带有@RequiresPermission注解的方法
     *//*
    @Pointcut("@annotation(org.example.annotation.CheckPermission)")
    public void permissionPointcut() {}*/

    /**
     * 环绕通知：在目标方法执行前进行权限校验
     */
    @Around("@annotation(checkPermission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint,CheckPermission checkPermission) throws Throwable {
/*        // 获取方法上的权限注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        CheckPermission annotation = signature.getMethod().getAnnotation(CheckPermission.class);
        String requiredPermission = annotation.value();*/
        // 获取注解中允许的角色
        String[] allowedRoles  = checkPermission.value();

        // 直接从BaseContext获取当前用户角色
        String currentRole = BaseContext.getCurrentRole();

        // 校验用户是否拥有至少一个允许的角色
        boolean hasPermission = false;
        for (String role : allowedRoles ) {
            if (currentRole != null && currentRole.equals(role)) {
                hasPermission = true;
                break;
            }
        }

        // 未通过校验则抛出异常
        if (!hasPermission) {
            throw new AccessDeniedException("权限不足，需角色：" + Arrays.toString(allowedRoles ));
        }

        // 放行执行目标方法
        return joinPoint.proceed();
    }
}